package cn.harry.modular.ai.service.impl;

import cn.harry.common.exception.ApiException;
import cn.harry.modular.ai.core.enums.AiPlatformEnum;
import cn.harry.modular.ai.core.factory.AiModelFactory;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.harry.modular.ai.mapper.ApiKeyMapper;
import cn.harry.modular.ai.service.ApiKeyService;
import cn.harry.modular.ai.domain.ApiKey;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

import static cn.harry.modular.ai.enums.ErrorCodeConstants.API_KEY_NOT_EXISTS;

/**
 * AI API 密钥服务实现类
 *
 * @author harry
 * @公众号 Harry技术
 */
@Service
@RequiredArgsConstructor
public class ApiKeyServiceImpl extends ServiceImpl<ApiKeyMapper, ApiKey> implements ApiKeyService {

    @Resource
    private AiModelFactory modelFactory;

    @Override
    public ChatModel getChatModel(Long keyId) {
        ApiKey apiKey = validateApiKey(keyId);
        AiPlatformEnum platform = AiPlatformEnum.validatePlatform(apiKey.getPlatform());
        return modelFactory.getOrCreateChatModel(platform, apiKey.getApiKey(), apiKey.getUrl());
    }

    private ApiKey validateApiKey(Long keyId) {
        ApiKey apiKey = getById(keyId);
        if (apiKey == null) {
            throw new ApiException(API_KEY_NOT_EXISTS);
        }
        return apiKey;
    }
}
